const app = getApp();
const util = require("util.js")
const storage = require("storage.js")
const constant = require("../constant.js")

/**
 * 
 */
function doWeAppLogin(success, fail) {

  var that = this
  wx.checkSession({
    success: function() {
      try {
        var sessionResult = wx.getStorageSync(storage.keys.session)
        var openidResult = wx.getStorageSync(storage.keys.openid)
        if (sessionResult && openidResult && sessionResult != "" && openidResult != "") {
          console.log("登录中，storage也存在数据, 直接返回成功回调函数")
          //typeof success == "function" && success(sessionResult, openidResult)
          _doLogin(success, fail);
        } else {
          _doLogin(success, fail);
        }
      } catch (e) {
        console.log(e)
        console.log("登录中，storage不存在数据, 重新登录")
        _doLogin(success, fail);
      }
    },
    fail: function() {
      console.log("登录态过期, 重新登录")
      _doLogin(success, fail);
    }
  })
}

function _doLogin(success, fail) {
  var that = this;
  wx.login({
    success: function(res) {
      if (res.code) {
        console.log("小程序登录成功, 跳转到成功处理逻辑...")
        _handleWeAppLoginSuccess(res, success, fail) // 发起成功回调
      } else {
        console.log("小程序登录失败, 跳转到失败处理逻辑...")
        _hanldeWeappLoginFail(res, fail)
      }
    },
    fail: function(res) {
      console.log("小程序登录失败, 跳转到失败处理逻辑...")
      console.log(res)
      _hanldeWeappLoginFail(res, fail)
    }
  })
}

// 处理小程序登录成功
function _handleWeAppLoginSuccess(res, success, fail) {

  console.log("小程序登录成功, 开始根据code [" + res.code + "]获取session与openid")
  var env = typeof app.globalData.prod == 'function' ? app.globalData.prod() : app.globalData.prod;
  wx.request({
    url: constant.api(env).auth.prepare + res.code,
    method: 'GET',
    success: function(res) {

      if (res.data.code == "0") {
        var session = res.data.data.session_key;
        var openid = res.data.data.openid;

        try {
          wx.setStorageSync(storage.keys.session, session)
          wx.setStorageSync(storage.keys.openid, openid)
          console.log("缓存session与openid成功，直接跳转到成功回调函数")
          typeof success == "function" && success(session);
        } catch (e) {
          console.log(e)
          console.log("缓存session与openid失败: " + e)
        }
      } else {
        console.log("获取session与openid失败")
        console.log("request openid occurs error with code[" + res.data.code + "] message[" + res.data.message + "]")
      }
    },
    fail: function(response) {
      console.log("获取session与openid网络请求失败")
      console.log(response)
    }
  })
}

// 处理小程序登录失败
function _hanldeWeappLoginFail(res, fail) {
  console.log("直接返回失败回调函数")
  typeof fail == "function" && fail(res)
}

function getUserInfo(params, success, fail) {
  doWeAppLogin(
    function(sessionKey) {

      console.log("小程序静默授权成功， 开始准备获取用户信息");

      wx.getSetting({
        success: function(res) {
          if (res.authSetting['scope.userInfo']) {
            console.log("已经授权，可以直接调用 getUserInfo 获取头像昵称")
            wx.getUserInfo({
              withCredentials: true,
              success: function(res) {
                _handleGetUserInfoSuccess(res.iv, res.encryptedData, sessionKey, success, fail)
              },
              fail: function() {
                openUserInfo();
              }
            })
          } else {
            // 开始弹窗授权
            app.globalData.authSuccess = success;
            app.globalData.authFail = fail;
            app.globalData.authKey = sessionKey;
            wx.navigateTo({
              url: params.authUrl ? params.authUrl : '../auth/auth',
            })
          }
        }
      })
    },
    function() {
      console.log("do weapp Login faild, get none user info");
    }
  )
}

function openUserInfo() {
  wx.openSetting({
    success: (res) => {
      console.log(res);
    },
    fail: (res) => {
      console.log(res);
    },
    complete: (res) => {
      console.log(res);
    },
  })
}

function _handleGetUserInfoSuccess(iv, encryptedData, sessionKey, success, fail, stopredirect) {

  try {
    var unionid = wx.getStorageSync(storage.keys.unionid)
    var mobile = wx.getStorageSync(storage.keys.mobile)
    if (unionid) {
      if (mobile) {
        typeof success == "function" && success(sessionKey)
      } else {
        _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect);
      }
    } else {
      _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect);
    }
  } catch (e) {
    console.log(e);
    _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect);
  }
}

function _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect) {
  var env = typeof app.globalData.prod == 'function' ? app.globalData.prod() : app.globalData.prod;
  wx.request({
    url: constant.api(env).auth.login,
    data: {
      'session-key': sessionKey,
      'iv': iv,
      'encrypted-data': encryptedData
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      if (res.data.code == "0") {
        try {
          var data = res.data.data;
          console.log("get wechat data" + data);

          wx.request({
            url: constant.api(app.globalData.pord).url + '/tencent-auth',
            method: 'GET',
            header: {
              'content-type': 'application/json'
            },
            dataType: 'json',
            responseType: 'text',
            success: function (res) {
              if (res.data.data.tencetAuth.mock) {
                wx.setStorageSync(storage.keys.unionid, res.data.data.tencetAuth.unionid)
              } else {
                wx.setStorageSync(storage.keys.unionid, data.account.unionid)
              }
            },
            fail: function () {
              wx.setStorageSync(storage.keys.unionid, data.account.unionid)
            }
          })
          
          var mobile = wx.getStorageSync(storage.keys.mobile)
          //typeof success == "function" && success(data.account.unionid)
          if (mobile) {
            typeof success == "function" && success(data.account.unionid)
          } else {
            wx.request({
              url: constant.api(app.globalData.pord).url + '/get-mobile?unionid=' + data.account.unionid,
              method: 'POST',
              data: {
                headimgurl: data.account.headimgurl,
                nickname: data.account.nickname
              },
              header: {
                'content-type': 'application/json'
              },
              dataType: 'json',
              responseType: 'text',
              success: function(res) {
                if (res.data.code == "0" && res.data.data.mobile) {
                  wx.setStorageSync(storage.keys.mobile, res.data.data.mobile)
                  typeof success == "function" && success(data.account.unionid)
                  // wx.reLaunch({
                  //   url: '/pages/mall/mall'
                  // })
                } else {
                  typeof success == "function" && success(data.account.unionid)
                  // wx.reLaunch({
                  //   url: '../../pages/mobile-bind/mobile-bind',
                  // })
                }
              },
              fail: function() {
                wx.reLaunch({
                  url: '../../pages/mobile-bind/mobile-bind',
                })
              }
            })

          }
          
        } catch (e) {
          console.log(e)
          typeof fail == "function" && fail()
        }
      } else {
        console.log("request userinfo occurs error with code[" + res.data.code + "] message[" + res.data.message + "]")
      }
    },
    fail: function(respnse) {
      //console.log("request userinfo faild");
      typeof fail == "function" && fail()
    }
  })
}

module.exports = {
  login: doWeAppLogin,
  getUserInfo: getUserInfo,
  _handleGetUserInfoSuccess: _handleGetUserInfoSuccess
}